<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* 原文链接：https://blog.csdn.net/shenwen522519753/article/details/104071606 */
        #box {
            width: 50vw;
            height: 50vh;
            border: 1px solid;
            font-size: 14px;
            overflow: hidden auto;
            padding: 0 10px;

            /* 设置光标颜色：*/
            /* caret-color: green; */
            /* caret-shape: block; */
            /* 防止全局设置 -webkit-user-select: none 后不会获取焦点 */
            -webkit-user-select: text;
            /* 
            清除编辑器获取焦点时的默认样式：
            -webkit-tap-highlight-color:rgba(0,0,0,0);
            -webkit-user-modify:read-write-plaintext-only;
            outline:none;
            */
        }

        /* 设置提示文字 */
        #box:empty::before {
            content: attr(placeholder);
            color: #999;
        }

        #box:focus::before {
            content: none;
        }
    </style>
</head>

<body>
    <!-- https://blog.csdn.net/qq_33368846/article/details/85265016
    前端之路：contenteditable 换行踩坑心得 -->
    <div id="box" contenteditable="true" placeholder="请输入"></div>
    <script>
        /*光标处插入html代码，参数是String类型的html代码，例子："<p>猪头诺</p>"*/
        function insertHtml(html) {
            var sel, range;
            if (window.getSelection) {
                // IE9 或 非IE浏览器
                sel = window.getSelection();
                if (sel.getRangeAt && sel.rangeCount) {
                    range = sel.getRangeAt(0);
                    range.deleteContents();
                    // Range.createContextualFragment() would be useful here but is
                    // non-standard and not supported in all browsers (IE9, for one)
                    var el = document.createElement("div");
                    el.innerHTML = html;
                    var frag = document.createDocumentFragment(),
                        node, lastNode;
                    while ((node = el.firstChild)) {
                        lastNode = frag.appendChild(node);
                    }
                    range.insertNode(frag);
                    // Preserve the selection
                    if (lastNode) {
                        range = range.cloneRange();
                        range.setStartAfter(lastNode);
                        range.collapse(true);
                        sel.removeAllRanges();
                        sel.addRange(range);
                    }
                }
            } else if (document.selection && document.selection.type != "Control") {
                // IE < 9
                document.selection.createRange().pasteHTML(html);
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            //兼容处理，统一换行时的元素渲染
            document.execCommand("defaultParagraphSeparator", false, "p");
            const box = document.getElementById('box')
            box.addEventListener('mouseup', (e) => {
                var selection = document.getSelection()
                var selectionText = selection.toString()
                console.log('selectionText', selectionText)
                console.log('e.target', e.target)
                if (selectionText) {
                    box.innerHTML = box.innerHTML.replace(/selectionText/)
                }
            })

            box.addEventListener('keydown', (e) => {
                var selection = document.getSelection()
                var selectionText = selection.toString()
                console.log('selectionText', selectionText)
                console.log('e.target', e.target)
                if (e.keyCode === 13) {
                    // insertHtml('<p></p>')
                    // e.preventDefault()
                }
            })
        })
    </script>
</body>

</html>